import './index.less'
import TodoHeader from './components/header'
import emoji from 'emoji-regex'
import { useRoute } from 'vue-router'
import {
	computed,
	defineComponent,
	nextTick,
	onMounted,
	onUnmounted,
	ref,
	watch
} from 'vue'
import { useStore } from '@/store'
import { addTask, alertTodoTitle, deleteTask, updateTask } from '@/http/func'
import { getElementInvertColor } from '@/utils'
import { Task } from '@/types/list'
import { useModal } from '@/plugins/modal/api'
import { useToast } from '@/plugins/toast/api'
// import { useActionSheet } from '@/plugins/action-sheet/api'
import More from './components/more'
import SetTheme from './components/setTheme'

export default defineComponent({
	name: 'todos',
	components: { TodoHeader, More },
	setup() {
		const route = useRoute()
		const store = useStore()
		const id = route.params.id
		const todo = store.state.list.list.find((v) => v.id === id)

		const titleColor = ref('')
		const taskText = ref('')
		const expend = ref(false)
		const hide = ref(false)
		const hideTitle = ref(false)
		const themePopupShow = ref(false)
		const theme = ref<string[]>([])

		const obser = ref<IntersectionObserver>()

		const todoList = computed(() => todo!.tasks.filter((task) => !task.isDone))
		const todoedList = computed(() => todo!.tasks.filter((task) => task.isDone))

		nextTick(() => {
			const target = document.querySelector('.todo-title')
			const root = document.querySelector('.todo-content')
			obser.value = new IntersectionObserver(interObserCallback, {
				root,
				threshold: [0, 0.25, 0.75, 1]
			})
			target && obser.value.observe(target)
		})

		onMounted(() => {
			titleColor.value = getElementInvertColor('.todo')
		})

		onUnmounted(() => {
			obser.value?.disconnect()
		})

		// 每次改变需要更新下state 缓存至本地
		watch(todo!, () => {
			store.commit('list/SET_LIST', store.state.list.list)
		})

		const title = computed(() => {
			if (todo?.icon && emoji().test(todo?.icon)) {
				return todo.icon + todo.title
			} else {
				return todo!.title
			}
		})

		const interObserCallback = (entries: IntersectionObserverEntry[]) => {
			// console.log('entries', entries)
			const ratio = entries[0].intersectionRatio
			if (ratio < 0.75) {
				hideTitle.value = true
			} else {
				hideTitle.value = false
			}
		}

		const changeName = async (e: any) => {
			let value = e.target.value,
				icon = 'list'
			// 未发生变化则不去请求接口
			if (value === title.value) return

			const match = emoji().exec(value)
			if (match && match.index === 0) {
				icon = match[0]
				value = value.replace(match[0], '')
			}
			const params = {
				id: todo!.id,
				title: value,
				icon
			}
			await alertTodoTitle(params)
			todo!.title = value
			todo!.icon = icon
			document.title = value
		}

		const remove = async (index: number) => {
			useModal({
				content: `确认删除“${todo?.tasks[index].todo}”待办事项`,
				async confirm() {
					try {
						await deleteTask({ lid: todo!.id, index })
						todo!.tasks.splice(index, 1)
					} catch (error) {
						console.log('error', error)
					}
				}
			})
		}

		const add = async (e: KeyboardEvent) => {
			if (!taskText.value.trim()) {
				useToast({
					text: '不可以添加空的任务'
				})
				return
			}
			if (e.code === 'Enter') {
				const { data } = await addTask({
					listId: todo!.id,
					todo: taskText.value
				})
				todo?.tasks.push(data)
				taskText.value = ''
			}
		}

		const setDone = async (item: Task, index: number) => {
			const bool = !item.isDone
			try {
				updateTaskInfo(index, {
					...item,
					isDone: bool
				})
				await updateTask({
					listId: todo!.id,
					index,
					isDone: bool
				})
			} catch (error) {
				updateTaskInfo(index, {
					...item,
					isDone: !bool
				})
			}
		}

		// 更新state数据
		const updateTaskInfo = (index: number, item: Task) => {
			todo?.tasks.forEach((task, i) => {
				if (index === i) {
					Object.keys(item).forEach((key) => {
						task[key] = item[key]
					})
				}
			})
		}

		const rightClick = () => {
			// useActionSheet({
			// 	title: '列表选项',
			// 	showCancel: true,
			// 	options: [
			// 		{ label: '设置主题', value: 0 },
			// 		{ label: '删除列表', value: 1 }
			// 	],
			// 	select(value) {
			// 		console.log(value)
			// 		switch (value) {
			// 			case 0:
			// 				themePopupShow.value = true
			// 				break
			// 			case 1:
			// 				break
			// 			default:
			// 				break
			// 		}
			// 	}
			// })
			themePopupShow.value = true
		}

		const setTheme = (val: string[]) => {
			console.log('theme', val)
			theme.value = val
		}

		return () => {
			const list = (tasks: Task[]) => (
				<ul class="todo-list">
					{tasks?.map((item) => (
						<li class="todo-list-item">
							<touch-slide
								v-slots={{
									default: () => (
										<div class="todo-list-item-content">
											<i
												class="icon iconfont todo-list-item-select"
												style={{ color: theme.value[1] }}
												onClick={() => setDone(item, item.index)}
											>
												{item.isDone ? '\ue690' : '\ue691'}
											</i>
											<span
												class={{
													'todo-list-item-txt': true,
													done: item.isDone
												}}
											>
												{item.todo}
											</span>
											<i class="icon iconfont todo-list-item-matter">
												&#xe66e;
											</i>
										</div>
									),
									right: () => (
										<div
											class="todo-list-item-delete"
											onClick={() => remove(item.index)}
										>
											删除
										</div>
									)
								}}
							/>
						</li>
					))}
				</ul>
			)

			return (
				<div class="page">
					<div class="todo" style={{ backgroundColor: theme.value[0] }}>
						<TodoHeader
							class="todo-header"
							theme={theme.value}
							showTitle={hideTitle.value}
							title={title.value}
							titleColor={titleColor.value}
							onRightHandler={rightClick}
						/>
						<div class="todo-content">
							<div class={{ 'todo-title': true, hide: hideTitle.value }}>
								<input
									style={{ color: theme.value[1] || titleColor.value }}
									type="text"
									value={title.value}
									onBlur={changeName}
								/>
							</div>
							{list(todoList.value)}
							<div class="done-list" v-show={todoedList.value.length > 0}>
								<div
									class="done-list-title"
									style={{ backgroundColor: theme.value[0] }}
									onClick={() => (hide.value = !hide.value)}
								>
									<div class="done-list-title-box">
										<i class={{ icon: true, iconfont: true, hide: hide.value }}>
											&#xe672;
										</i>
										<span>已完成</span>
									</div>
								</div>
								<div class={{ 'done-list-content': true, hide: hide.value }}>
									{list(todoedList.value)}
								</div>
							</div>
						</div>
						<div
							class={['todo-footer', expend.value ? 'focus' : 'default']}
							style={{ backgroundColor: theme.value[0] }}
						>
							<div class="todo-footer-add">
								<i class="icon iconfont">
									{expend.value ? '\ue691' : '\ue642'}
								</i>
								<input
									type="text"
									placeholder="添加任务"
									onKeypress={add}
									onFocus={() => (expend.value = true)}
									onBlur={() => (expend.value = false)}
									v-model={taskText.value}
								/>
							</div>
						</div>
					</div>
					<More
						v-model={[themePopupShow.value, 'visible', ['modifier']]}
						v-slots={{
							theme: () => <SetTheme onSetTheme={setTheme} />
						}}
					/>
				</div>
			)
		}
	}
})
